package com.yiwenup.leetcode.top_interview_150;

import com.yiwenup.leetcode.ListNode;

/**
 * 文件描述
 *
 * @Project struct-algorithm
 * @Package com.yiwenup.leetcode.top_interview_150
 * @Author yiwenup
 * @Date 2024-12-12 22:13:45
 * @Description https://leetcode.cn/problems/add-two-numbers/description/?envType=study-plan-v2&envId=top-interview-150
 */
public class No0002 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode(-1);
        ListNode curr = ans;
        int tag = 0;
        while(l1 != null && l2 != null) {
            int add = l1.val + l2.val + tag;
            tag = 0;
            if(add >= 10) {
                add -= 10;
                tag = 1;
            }
            curr.next = new ListNode(add);
            curr = curr.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        ListNode leave = l1 == null ? l2 : l1;
        if(tag == 0) {
            curr.next = leave;
        } else {
            while(leave != null) {
                int add = leave.val + tag;
                tag = 0;
                if(add >= 10) {
                    add -= 10;
                    tag = 1;
                }
                curr.next = new ListNode(add);
                curr = curr.next;
                leave = leave.next;
            }
            if(tag == 1) {
                curr.next = new ListNode(1);
            }
        }

        return ans.next;
    }
}
